<template>
  <div id="SpaceManagePage">
    <a-flex justify="space-between" style="margin:15px 0">
      <h2>空间管理</h2>
      <a-space class="createBtn">
        <a-button type="primary" ghost href="/space_analyze?queryPublic=1" :icon="h(PieChartOutlined)" target="_blank">分析公共图库</a-button>
        <a-button type="primary" ghost href="/space_analyze?queryAll=1" :icon="h(BarChartOutlined)" target="_blank">分析全部空间</a-button>
        <a-button type="primary" href="/add_space" target="_blank">+ 新建空间</a-button>
      </a-space>
    </a-flex>
    <!--    搜索功能-->
    <div class="searchModel">
      <a-form layout="inline" :model="searchParams" @finish="doSearch">
        <a-form-item label="空间名称" name="spaceName">
          <a-input
            v-model:value="searchParams.spaceName"
            placeholder="请输入空间名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="空间级别" name="spaceLevel">
          <a-select
            v-model:value="searchParams.spaceLevel"
            :options="SPACE_LEVEL_OPTIONS"
            placeholder="请输入空间级别"
            style="min-width: 180px"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="空间类别" name="spaceType">
          <a-select v-model:value="searchParams.spaceType"
            :options="SPACE_TYPE_OPTIONS" placeholder="请选择空间类别" style="min-width: 180px" allow-clear
          />
        </a-form-item>
        <a-form-item label="用户 id" name="userId">
          <a-input v-model:value="searchParams.userId" placeholder="请输入用户 id" allow-clear />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" :icon="h(SearchOutlined)">搜索</a-button>
        </a-form-item>
      </a-form>
    </div>
    <!--    空间管理模块-->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      :scroll="{ x: 1500 }"
    >
      <template #headerCell="{ column }"></template>

      <template #bodyCell="{ column, record }">
        <!--        设置空间级别文本展示-->
        <template v-if="column.dataIndex === 'spaceLevel'">
          <a-tag :color="record.spaceLevel === 0 ? 'green' : record.spaceLevel === 1 ? 'orange' : 'red'">{{ SPACE_LEVEL_MAP[record.spaceLevel] }}</a-tag>
        </template>
        <!-- 空间类别 -->
        <template v-if="column.dataIndex === 'spaceType'">
          <a-tag :color="record.spaceType === 0 ? '#87d068' : '#108ee9'">{{ SPACE_TYPE_MAP[record.spaceType] }}</a-tag>
        </template>
        <!-- 使用情况格式化 -->
        <template v-if="column.dataIndex === 'spaceSpaceInfo'">
          <div>数量：{{ record.totalCount }} / {{ record.maxCount }}</div>
          <a-tooltip :title="'大小：' + formatSize(record.totalSize) +  '/' + formatSize(record.maxSize)">
            <a-progress :percent="(record.totalSize/record.maxSize).toFixed(1)" size="small" />
          </a-tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <!--  按钮操作区  -->
        <template v-else-if="column.key === 'action'">
          <a-button type="link" :href="`/add_space?id=${record.id}`" target="_blank"
            >编辑
          </a-button>
          <a-button type="link" danger @click="doDelete(record.id)">删除</a-button>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import {computed, h, onMounted, reactive, ref} from 'vue'
import { deleteSpaceUsingPost, listSpaceByPageUsingPost } from '@/api/SpaceController'
import { message } from 'ant-design-vue'
import {SPACE_LEVEL_MAP, SPACE_LEVEL_OPTIONS, SPACE_TYPE_MAP, SPACE_TYPE_OPTIONS} from '@/constants/space'
import { PieChartOutlined, BarChartOutlined, SearchOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import { formatSize } from '../../utils'

dayjs.locale('zh-cn')

// 搜索空间数据
const doSearch = () => {
  // 每次搜索从第一页开始搜，否则可能搜不到
  searchParams.current = 1
  fetchData()
}

//点击删除按钮删除记录操作
const doDelete = async (id: string) => {
  if (!id) return
  // 调用后端方法，根据id删除记录
  const res = await deleteSpaceUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 再次获取数据刷新
    fetchData()
  } else {
    message.error('删除失败，' + res.data.message)
  }
}

// 表格列标题定义
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '空间名称',
    dataIndex: 'spaceName',
  },
  {
    title: '空间级别',
    dataIndex: 'spaceLevel',
  },
  {
    title: '空间类别',
    dataIndex: 'spaceType',
  },

  {
    title: '使用情况',
    dataIndex: 'spaceSpaceInfo',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

//获取空间数据接收
const dataList = ref<API.SpaceVO>([]) //记录空间数组
const total = ref(0) // 总空间条数
// 搜索条件
const searchParams = reactive<API.SpaceQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 获取后端空间数据
const fetchData = async () => {
  const res = await listSpaceByPageUsingPost({
    ...searchParams,
  })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取空间数据失败，' + res.data.message)
  }
}

// 让页面第一次刷新时获取一次，之后不必重复获取
onMounted(() => {
  fetchData()
})

//分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}
</script>
<style scoped>
#SpaceManagePage {
}

.searchModel {
  padding-bottom: 5px;
}

.reviewTag {
  text-align: center;
}
</style>
